<template>
  <el-form ref="form" :model="form" :rules="rules" class="form">
    <div class="title">欢迎登录</div>
    <div class="register">
      <span class="content">没有账户？</span>
      <span class="btn imgBox" @click="$emit('shift')">免费注册
        <img src="@/assets/images_login/dl_point_icon.png" alt="dl_point">
      </span>
    </div>
    <div class="input">
      <el-form-item prop="username" :error="usernameError">
        <template #error="scoped">
          <span class='error-message'>{{scoped.error}}</span>
        </template>
        <div class="input-box">
          <input
          v-model="form.username"
          type="text"
          placeholder="输入账号"
          >
          <div class="imgBox">
            <img class="input-icon" src="@/assets/images_login/user_icon.png" alt="user_icon">
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="password">
        <template #error="scoped">
          <span class='error-message'>{{scoped.error}}</span>
        </template>
        <div class="input-box">
          <input v-model="form.password" type="password"
          placeholder="输入密码"

          @keyup.enter="handleLogin"
          >
          <div class="imgBox">
            <img class="input-icon" src="@/assets/images_login/pwd_icon.png" alt="pwd_icon">
          </div>
        </div>
      </el-form-item>
    </div>

    <el-form-item prop="code" v-if="captchaOnOff">
      <template #error="scoped">
        <span class='error-message'>{{scoped.error}}</span>
      </template>
      <el-input
        v-model="form.code"
        auto-complete="off"
        placeholder="验证码"
        style="width: 63%"
        @keyup.enter.native="handleLogin"
      >
        <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
      </el-input>
      <div class="login-code imgBox">
        <img :src="codeUrl" @click="getCode" class="login-code-img"/>
      </div>
    </el-form-item>
    <div class="forget" @click="forgetVisible=true">忘记密码？</div>

    <el-button
      :class="{btnClass:fullIn}"
      :loading="loading"
      size="medium"
      type="primary"
      class="formBtn"
      @click.native.prevent="handleLogin"
    >
      <span v-if="!loading">登录</span>
      <span v-else>登录中...</span>
    </el-button>
    <!-- <div style="float: right;" v-if="register">
      <router-link class="link-type" :to="'/register'">立即注册</router-link>
    </div> -->
    <div class="protocol">
      <input  type="checkbox" id="protocol" v-model="protocol">
      <label for="protocol"></label>
      <p class="content">登录即代表您同意 <span @click="dialogVisible=true;articleType=0">平台服务协议</span> 和 <span @click="dialogVisible=true;articleType=1">隐私政策</span></p>
    </div>

    <Dialog :visible.sync="dialogVisible" :type="articleType"></Dialog>
    <el-dialog width="5.79rem" :title="dialog.title" :visible.sync="forgetVisible" class="forget">
      <div class="forget-password">
        <div class="forget-password-icon">
          <img src="@/assets/images_login/wjmm_icon.png" alt="wjmm_icon">
        </div>
        <div class="forget-password-content" >
          <div>{{dialog.content}}</div>
          <div>客服热线：<span>0757-82138330</span></div>
        </div>
      </div>
      <template #footer>
        <div class="forget-password-footer">
          <div class="btn" @click="forgetVisible=false">我知道了</div>
        </div>
      </template>
    </el-dialog>
  </el-form>
</template>

<script>
import { getCodeImg,shopRegister } from "@/api/login";
import { sessionCache} from '@/plugins/cache'
import Dialog from './dialog'
import pubsub from 'pubsub-js'

export default {
  name:'LoginForm',
  components:{
    Dialog
  }, beforeRouteEnter(to, from, next) {
    console.log('enter');
    next()
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当守卫执行前，组件实例还没被创建
  },
  beforeRouteUpdate(to, from, next) {
    console.log('update');
    next()
    // 在当前路由改变，但是该组件被复用时调用
    // 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
    // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave(to, from, next) {
    console.log('leave');
    next()
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  },
  data(){
    return {
      automaticLogIn : false,
      forgetVisible:false,
      articleType:0,
      dialogVisible:false,
      loading:false,
      captchaOnOff:false,
      protocol:true,
      codeUrl:'',
      usernameError:'',
      form:{
        username:'',
        password:'',
        code:'',
        uuid:'',
        rememberMe:false
      },
      dialog:{
        title:'忘记密码',
        content:'请联系平台客服重置密码！'
      },
      rules:{
        username:{
          required:true,
          trigger:'blur',
          message:'请输入用户名',
        },
        password:{
          required:true,
          trigger:'blur',
          message:'请输入密码'
        }
      },
    }
  },
  created(){
    pubsub.subscribe('handleNoPermission', (_, msg) => {
      console.log(msg);
      this.dialog.title = '提示'
      this.dialog.content = '您好！当前账户暂未分配权限，请稍后再试，或联系平台客服处理'
      this.forgetVisible = true
    })
    this.getCode()
    this.getCookie()
  },
  computed:{
    fullIn(){
      return Boolean(this.form.username && this.form.password && this.protocol)
    }
  },
  methods:{
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.form.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = sessionStorage.getItem('username')
      const password = sessionStorage.getItem('password')
      const automaticLogIn = sessionStorage.getItem('autologin')
      this.form.username = username === undefined ? this.form.username : username
      this.form.password = password === undefined ? this.form.password : password
      if(automaticLogIn){
        this.automaticLogIn = automaticLogIn
        sessionStorage.removeItem('autologin')
        sessionStorage.removeItem('username')
        sessionStorage.removeItem('password')
        this.handleLogin()
      }
    },
    login(){
      if(!this.protocol){
        return this.$modal.msgWarning('请先阅读协议')
      }
      this.loading = true;
      //明文传输
      //00:内部用户(云仓管理)，11:用户（智慧云仓）
      // const goSystemDefaultPage = {
      //   '00':'storage/storageIndex',
      //   '11':'cStorage/cWarehouseIn'
      // }
      this.$store.dispatch("Login", this.form).then(() => {
        this.$router.push('/defaultPath')
      }).catch(() => {
        this.usernameError = '用户名或密码错误'
        if (this.captchaOnOff) {
          this.getCode();
        }
      }).finally(()=>{
        this.loading = false;
      });
    },
    handleLogin() {
      if(this.automaticLogIn){
        this.login()
      }else{
        this.$refs.form.validate(valid => {
          if (valid) {
            this.login()
          }
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.btnClass{
  background-color:#c19765!important;
}
.forget-password{
  display: flex;
  align-items: center;

  &-icon{
    width: .75rem;
    height: .75rem;
    img{
      width: 100%;
    }
  }

  &-content{
    margin-left: .25rem;
    color: #333333;
    font-size: .18rem;
    line-height: .3rem;
    span{
      font-style: italic;
      font-weight: 700;
    }
  }

  &-footer{
    display: flex;
    justify-content: flex-end;
    .btn{
      width: 1.15rem;
      height: .4rem;
      line-height: .4rem;
      text-align: center;
      background-color: #C69766;
      color: #fff;
      border-radius: .04rem;
      cursor: pointer;
    }
  }
}

::v-deep .forget .el-dialog:not(.is-fullscreen) {
  margin-top: 42vh !important;
}

::v-deep .forget .el-dialog__header{
  background-color: #EEEEEE;
}
::v-deep .forget .el-dialog__body{
  padding: .2rem .2rem .2rem .25rem;
}
</style>
